package org.jeecg.modules.chg.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.JwMsgTemplateModel;
import org.jeecg.common.system.vo.JwidModel;
import org.jeecg.common.system.vo.WeChatPayModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.pay.WXPayUtils;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.jeecg.modules.chg.entity.ChgFees;
import org.jeecg.modules.chg.entity.ChgPayments;
import org.jeecg.modules.chg.mapper.ChgFeesMapper;
import org.jeecg.modules.chg.service.IChgArrearsService;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.chg.service.IChgMpService;
import org.jeecg.modules.chg.service.IChgPaymentsService;
import org.jeecg.modules.chg.vo.ChgChargeFeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 公众号微信支付
 * @Author: jeecg-boot
 * @Date:   2022-05-08
 * @Version: V1.0
 */
@Service
public class ChgMpServiceImpl extends ServiceImpl<ChgFeesMapper, ChgFees> implements IChgMpService {

	@Autowired
	private IArcAccountService accountService;
	@Autowired
	private IChgArrearsService arrearsService;
	@Autowired
	private IChgFeesService chgFeesService;
	@Autowired
	private IChgPaymentsService paymentsService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private WXPayUtils wxPayUtils;
	@Autowired
	private RedisUtil redisUtil;

	@Override
	@Transactional
	public Result<?> createMpOrder(JwidModel jwidModel, JSONObject orderObj)throws Exception {
		if (null == jwidModel){
			return Result.error("没有公众号账号信息");
		}

		Double receFee = orderObj.getDouble("receFee");//应缴 （账单）
		Double realFee = orderObj.getDouble("realFee");//realFee, //实缴：应收-余额
		Double payFee = orderObj.getDouble("payFee");//实付,
		//缴费账户对应 用户水表信息
		List<ArcAccountCusVO> cusVOList = accountService.queryAccount(null
				, null,orderObj.getString("accCode"));
		ArcAccountCusVO cusVO = cusVOList.get(0);

		String batchKey=orderObj.getString("accCode");
		if(oConvertUtils.isNotEmpty(batchKey)) {
			Object bo = redisUtil.get("wx_create_bill_"+batchKey);
			if (null != bo) {
				return Result.error("该账户正在支付中，请稍后查账后再试");
			}
			redisUtil.set("wx_create_bill_"+batchKey, "auditing", 1 * 60);
		}

		boolean isPreStore=false;

		if(null != orderObj && null != orderObj.get("arrearIds")){
			ArrayList arrearIds= (ArrayList) orderObj.get("arrearIds");
			if (null != arrearIds && arrearIds.size()>0){

//				if( null == cusVO.getAccCode() ||  !"8022030".equals(cusVO.getAccCode()) ){
//					return Result.error("微信缴费试用阶段仅供特定户号缴费");
//				}

//				if(jwidModel.getTenantId() == 8 && !"0061".equals(cusVO.getAccCode())){
//					return Result.error("微信缴费试用阶段仅供特定户号缴费");
//				}

				/**如果预充-不欠费  应缴（账单）金额 =0 */
				//if (cusVO.getAccBalance().doubleValue() >= receFee){
				//	//余额 充足，直接缴费
				//
				//	//校验余额，
				//	List<ChgArrears> chgArrearLs= arrearsService.listByIds(arrearIds);
				//
				//	// 使用匿名比较器排序
				//	Collections.sort(chgArrearLs, new Comparator<ChgArrears>() {
				//		@Override
				//		public int compare(ChgArrears p1, ChgArrears p2) {
				//			return p1.getReadMonth().compareTo(p2.getReadMonth()); //升序
				//		}
				//	});
				//
				//	for (ChgArrears arrears : chgArrearLs) {
				//		Result<?> result = chgFeesService.storedCharge(arrears);
				//		if (!result.isSuccess()){
				//			return Result.error(result.getMessage());
				//		}
				//	}
				//	return Result.OK("成功");
				//}else {
					ChgChargeFeeVo chargeFeeVo = new ChgChargeFeeVo();
					chargeFeeVo.setAccCode(orderObj.getString("accCode"));
				System.out.println(chargeFeeVo.getAccCode()+"-------------正在生成预订单------------");
					chargeFeeVo.setId(cusVO.getId());
					chargeFeeVo.setAccName(cusVO.getAccName());
					chargeFeeVo.setFeePayWay("3");//支付方式 3微信
					chargeFeeVo.setFeeTollWay("3");//收费方式 3余额预存（收费剩下）
					chargeFeeVo.setFeeWholeWay("01");//整收方式 实收
					//paymentsPage.setBillTypeId(null);//票据类型
					//paymentsPage.setFeePrintWay(null);//打印方式
					chargeFeeVo.setPayFee(new BigDecimal(payFee).setScale(2,BigDecimal.ROUND_HALF_UP));//实付|付款
					chargeFeeVo.setReceFee(new BigDecimal(receFee).setScale(2,BigDecimal.ROUND_HALF_UP));//应缴
					chargeFeeVo.setRealFee(new BigDecimal(realFee).setScale(2,BigDecimal.ROUND_HALF_UP));//实缴：应收-余额
					chargeFeeVo.setZeroFee(new BigDecimal(0).setScale(0,BigDecimal.ROUND_HALF_UP));//找零

					ChgPayments chgPayments=null;
					/**是否已存在预缴订单*/
					List<ChgPayments> list1 = paymentsService.list(new LambdaQueryWrapper<ChgPayments>()
							.eq(ChgPayments::getStatus, 0)
							.eq(ChgPayments::getAccCode, chargeFeeVo.getAccCode())
							.eq(ChgPayments::getFeePayWay,"3")
							.eq(ChgPayments::getPayFee,chargeFeeVo.getPayFee())
							.gt(ChgPayments::getFinancialDate,DateUtils.getDate("yyyy-MM-dd"))
							.orderByDesc(ChgPayments::getFinancialDate)
						);
					if(null != list1 && list1.size()>0){
						chgPayments=list1.get(0);
					}else{
						chgPayments = chgFeesService.storedPreCharge(chargeFeeVo,orderObj);
					}

					//应缴 （账单）-余额
					BigDecimal subPay= new BigDecimal(receFee).subtract(cusVO.getAccBalance())
							.setScale(2,BigDecimal.ROUND_HALF_UP);
					int payAmout = chargeFeeVo.getPayFee().multiply(new BigDecimal(100)).intValue();

					//单位精确分，化整数
					int amount= subPay.multiply(new BigDecimal(100)).intValue();

					if(payAmout != amount){
						amount=payAmout;
					}

					if( null != cusVO.getAccCode() && ("8022030".equals(cusVO.getAccCode()) )){
						amount=1;
					}

					orderObj.put("paymentId",chgPayments.getId());
					orderObj.put("notifyUrl","http://mws.usw.cn/boot/chg/mp/orderNotify");
//					orderObj.put("notifyUrl","http://mws.usw.cn/boot/chg/mp/orderNotify");
					orderObj.put("amount",amount);
					orderObj.put("openId",jwidModel.getOpenId());

					Result<?> mpOrder = this.createMpOrderPage(jwidModel, orderObj);
					if (mpOrder.isSuccess()){
						JSONObject orderResult = (JSONObject) mpOrder.getResult();
						String prepay_id = orderResult.getString("prepay_id");
						chgPayments.setPrepayId(prepay_id);

						//保存预支付Id
						paymentsService.update(new LambdaUpdateWrapper<ChgPayments>()
								.set(ChgPayments::getPrepayId,chgPayments.getPrepayId())
								.set(ChgPayments::getStatus,0)
								.eq(ChgPayments::getId,chgPayments.getId()));

						//这里是list来存储 传递到签名 辅助类
						long timestamp = System.currentTimeMillis()/1000;//系统的时间戳 DateUtils.getMillis()/1000
						String nonce_str = chgPayments.getId()+"_"+jwidModel.getTenantId();//maven引入微信的支付包就会有这个辅助类
						String packageStr = "prepay_id="+prepay_id;//下订单后会返回来给你订单号ID 这个要拼接

						ArrayList<String> list = new ArrayList<>();
						list.add(jwidModel.getWeixinAppid());//商户号ID
						list.add(String.valueOf(timestamp));
						list.add(nonce_str);
						list.add(packageStr);
						//加载签名
						String paySign = wxPayUtils.sign(wxPayUtils.buildSignMessage(list).getBytes(), jwidModel.getMchkeyPath());

						//需要把值返回前端调用 返回数据开始支付
						JSONObject resObject = new JSONObject();
						resObject.put("appId",jwidModel.getWeixinAppid());
						resObject.put("timeStamp", String.valueOf(timestamp));
						resObject.put("nonceStr", chgPayments.getId()+"_"+jwidModel.getTenantId());//_租户
						resObject.put("package", "prepay_id="+prepay_id);
						resObject.put("signType", "RSA");
						resObject.put("paySign", paySign);

						return Result.OK(resObject);
					}else {
						//删除预付款
						paymentsService.delMain(chgPayments.getId());
						return Result.error(mpOrder.getMessage());
					}
				//}
			}else{
				isPreStore=true;
			}
		}else{
			isPreStore=true;
		}
		if(isPreStore){
			ChgChargeFeeVo chargeFeeVo = new ChgChargeFeeVo();
			chargeFeeVo.setAccCode(orderObj.getString("accCode"));
			System.out.println(chargeFeeVo.getAccCode()+"-------------正在生成预订单------------");
			chargeFeeVo.setId(cusVO.getId());
			chargeFeeVo.setAccName(cusVO.getAccName());
			chargeFeeVo.setFeePayWay("3");//支付方式 3微信
			chargeFeeVo.setFeeTollWay("3");//收费方式 3余额预存（收费剩下）
			chargeFeeVo.setFeeWholeWay("01");//整收方式 实收
			//paymentsPage.setBillTypeId(null);//票据类型
			//paymentsPage.setFeePrintWay(null);//打印方式
			chargeFeeVo.setPayFee(new BigDecimal(payFee).setScale(2,BigDecimal.ROUND_HALF_UP));//实付|付款
			chargeFeeVo.setReceFee(new BigDecimal(receFee).setScale(2,BigDecimal.ROUND_HALF_UP));//应缴
			chargeFeeVo.setRealFee(new BigDecimal(realFee).setScale(2,BigDecimal.ROUND_HALF_UP));//实缴：应收-余额
			chargeFeeVo.setZeroFee(new BigDecimal(0).setScale(0,BigDecimal.ROUND_HALF_UP));//找零

			ChgPayments chgPayments=null;
			/**是否已存在预缴订单*/
			List<ChgPayments> list1 = paymentsService.list(new LambdaQueryWrapper<ChgPayments>()
					.eq(ChgPayments::getStatus, 0)
					.eq(ChgPayments::getAccCode, chargeFeeVo.getAccCode())
					.eq(ChgPayments::getFeePayWay,"3")
					.eq(ChgPayments::getPayFee,chargeFeeVo.getPayFee())
					.gt(ChgPayments::getFinancialDate,DateUtils.getDate("yyyy-MM-dd"))
					.orderByDesc(ChgPayments::getFinancialDate)
			);
			if(null != list1 && list1.size()>0){
				chgPayments=list1.get(0);
			}else{
				chgPayments = chgFeesService.storedPreCharge(chargeFeeVo,orderObj);
			}

			//应缴 （账单）-余额
			BigDecimal subPay= new BigDecimal(receFee).subtract(cusVO.getAccBalance())
					.setScale(2,BigDecimal.ROUND_HALF_UP);
			int payAmout = chargeFeeVo.getPayFee().multiply(new BigDecimal(100)).intValue();

			//单位精确分，化整数
			int amount= subPay.multiply(new BigDecimal(100)).intValue();

			if(payAmout != amount){
				amount=payAmout;
			}

			if( null != cusVO.getAccCode() && ("8022030".equals(cusVO.getAccCode()) )){
				amount=1;
			}

			orderObj.put("paymentId",chgPayments.getId());
			orderObj.put("notifyUrl","http://mws.usw.cn/boot/chg/mp/orderNotify");
//					orderObj.put("notifyUrl","http://mws.usw.cn/boot/chg/mp/orderNotify");
			orderObj.put("amount",amount);
			orderObj.put("openId",jwidModel.getOpenId());

			Result<?> mpOrder = this.createMpOrderPage(jwidModel, orderObj);
			if (mpOrder.isSuccess()){
				JSONObject orderResult = (JSONObject) mpOrder.getResult();
				String prepay_id = orderResult.getString("prepay_id");
				chgPayments.setPrepayId(prepay_id);

				//保存预支付Id
				paymentsService.update(new LambdaUpdateWrapper<ChgPayments>()
						.set(ChgPayments::getPrepayId,chgPayments.getPrepayId())
						.set(ChgPayments::getStatus,0)
						.eq(ChgPayments::getId,chgPayments.getId()));

				//这里是list来存储 传递到签名 辅助类
				long timestamp = System.currentTimeMillis()/1000;//系统的时间戳 DateUtils.getMillis()/1000
				String nonce_str = chgPayments.getId()+"_"+jwidModel.getTenantId();//maven引入微信的支付包就会有这个辅助类
				String packageStr = "prepay_id="+prepay_id;//下订单后会返回来给你订单号ID 这个要拼接

				ArrayList<String> list = new ArrayList<>();
				list.add(jwidModel.getWeixinAppid());//商户号ID
				list.add(String.valueOf(timestamp));
				list.add(nonce_str);
				list.add(packageStr);
				//加载签名
				String paySign = wxPayUtils.sign(wxPayUtils.buildSignMessage(list).getBytes(), jwidModel.getMchkeyPath());

				//需要把值返回前端调用 返回数据开始支付
				JSONObject resObject = new JSONObject();
				resObject.put("appId",jwidModel.getWeixinAppid());
				resObject.put("timeStamp", String.valueOf(timestamp));
				resObject.put("nonceStr", chgPayments.getId()+"_"+jwidModel.getTenantId());//_租户
				resObject.put("package", "prepay_id="+prepay_id);
				resObject.put("signType", "RSA");
				resObject.put("paySign", paySign);

				return Result.OK(resObject);
			}else {
				//删除预付款
				paymentsService.delMain(chgPayments.getId());
				return Result.error(mpOrder.getMessage());
			}
		}
		return Result.OK("没有欠费记录");
	}

	@Override
	@Transactional
	public Result<?> wehcatPayback(JwidModel jwidModel, String body, String nonceStr, String serialNo, String signature, String timestamp ) {

		//构造签名串

		//应答时间戳\n
		//应答随机串\n
		//应答报文主体\n
		String signStr = Stream.of(timestamp, nonceStr, body).collect(Collectors.joining("\n", "", "\n"));

		Map<String, String> map = new HashMap<>(2);
		try {
			//验证签名是否通过
			boolean result = verifiedSign(jwidModel,serialNo, signStr, signature);

			if(result){

				//JSONObject bodyOb = (JSONObject) JSONObject.parse(body);
				//JSONObject resourceOb=(JSONObject) bodyOb.get("resource");
				//String nonceStr = resourceOb.getString("nonce");

				//解密数据
				String plainBody = wxPayUtils.decryptBody(body,jwidModel.getWeixinMchkey());
				log.warn("解密后的明文:"+plainBody);

				JSONObject orderJson= (JSONObject) JSON.parse(plainBody);
				String attach = orderJson.getString("attach");


				//处理业务逻辑 TODO

				//响应微信 SUCCESS/FAIL
				map.put("code", "SUCCESS");
				map.put("message", "成功");
				return Result.OK(map);
			}

		} catch (Exception e) {
			log.error("微信支付回调异常:{}", e);
			return Result.error("微信支付回调异常:{}", e.getMessage());
		}
		return Result.error("");
	}

	@Override
	public Result<?> queryMpOrderState(JwidModel jwidModel, JSONObject orderObj) {

		ChgPayments chgPayments=null;
		if(null != orderObj && null != orderObj.get("package")) {
			String payPackage = orderObj.getString("package");
			String[] payPreArr = payPackage.split("=");//"prepay_id="+prepay_id
			if(null != payPreArr && oConvertUtils.isNotEmpty(payPreArr[1])){
				System.out.println(orderObj.toJSONString());
				//status=null,不管有没成功都有条预支付记录
				List<ChgPayments> paymentsList = paymentsService.selectPrePayOrder(payPreArr[1],null);
				if(null != paymentsList && paymentsList.size()>0){
					chgPayments = paymentsList.get(0);
				}
			}

			if(null == chgPayments){
				return Result.error("预支付订单不存在");
			}

			boolean prePayState=false;

			if(1 == chgPayments.getStatus() && oConvertUtils.isNotEmpty(chgPayments.getTransactionId())){
				//已支付成功- 回调已处理
				prePayState=true;
			}else{
				//查询预支付订单状态 payPreArr[1]
				try {
//					Result<?> preOrder = wxPayUtils.queryPreOrder(jwidModel, payPreArr[1]);
					/**
					 * {"amount":{"currency":"CNY","payer_currency":"CNY","payer_total":1,"total":1},"appid":"wxbc93defb209eb818","attach":""
					 * ,"bank_type":"OTHERS","mchid":"1625344192","out_trade_no":"1531267686257803266","payer":{"openid":"ombUS6RxgmyyAi9aqdQsTeveWBeU"}
					 * ,"promotion_detail":[],"success_time":"2022-05-30T21:34:54+08:00","trade_state":"SUCCESS","trade_state_desc":"支付成功"
					 * ,"trade_type":"JSAPI","transaction_id":"4200001425202205302805017124"}
					 * */
					Result<?> preOrder = wxPayUtils.queryPreOrderNo(jwidModel, chgPayments.getId());
					if(preOrder.isSuccess()){
						prePayState=true;
						JSONObject traObj=	JSONObject.parseObject(preOrder.getResult().toString());
						if(null !=traObj && oConvertUtils.isNotEmpty(traObj.getString("transaction_id"))){
							chgPayments.setTransactionId(traObj.getString("transaction_id"));
						}else{
							return Result.error("预支付核销异常"+traObj.getString("trade_state_desc"));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					return Result.error("预支付核销异常"+e.getMessage());
				}
			}

			if(prePayState){

				//业务核销处理
				boolean isPreStroe=false;

				//BigDecimal payFee = orderObj.getBigDecimal("payFee");//应付、应缴
				//Double receFee = orderObj.getDouble("receFee");//应收-账单费用

				Double receFee = orderObj.getDouble("receFee");// arrearMoney 应付、应缴 账单费用
				Double realFee = orderObj.getDouble("realFee");//realFee, //实缴：应收-余额
				Double payFee = orderObj.getDouble("payFee");//（应缴金额）实付  arrearMoney-余额 后的，
				ArrayList arrearIds=null;
				try{
					arrearIds= (ArrayList) orderObj.get("arrearIds");
					if(null == arrearIds || arrearIds.size() ==0 || "[]".equals(arrearIds.toString())){
						isPreStroe=true;
					}
				}catch (Exception e){
					isPreStroe=true;
				}

				ChgChargeFeeVo chargeFeeVo = new ChgChargeFeeVo();
				chargeFeeVo.setAccCode(orderObj.getString("accCode"));
				chargeFeeVo.setId(chgPayments.getAccountId());
				chargeFeeVo.setAccName(chgPayments.getAccName());
				chargeFeeVo.setFeePayWay("3");//支付方式 3微信
				chargeFeeVo.setFeeTollWay("3");//收费方式 3余额预存（收费剩下）
				chargeFeeVo.setFeeWholeWay("01");//整收方式 实收
				//paymentsPage.setBillTypeId(null);//票据类型
				//paymentsPage.setFeePrintWay(null);//打印方式
				if(isPreStroe){
					//预缴的，应缴是0 实缴是0
					chargeFeeVo.setReceFee(new BigDecimal(0));//应缴
					chargeFeeVo.setRealFee(new BigDecimal(0));//实缴：应收-余额
					arrearIds=null;
				}else{
					chargeFeeVo.setReceFee(new BigDecimal(receFee));//应缴
					chargeFeeVo.setRealFee(new BigDecimal(realFee));//实缴：应收-余额
				}
				chargeFeeVo.setPayFee(chgPayments.getPayFee());//实付
				chargeFeeVo.setZeroFee(new BigDecimal(0).setScale(0,BigDecimal.ROUND_HALF_UP));//找零

				Result<?> result = chgFeesService.mpCharge(chargeFeeVo, chgPayments, arrearIds);
				if(result.isSuccess()){
					//推送缴费成功通知
					JSONObject rsObject = (JSONObject) result.getResult();

					String accessToken = jwidModel.getAccessToken();
					JwMsgTemplateModel msgTemplate = sysBaseAPI.getMsgFeeBillTemplate(jwidModel.getId(), CommonSendStatus.MSG_PAY_SUCCESS_NOTICE);
					if(null == msgTemplate){
						return Result.error("缴费成功，缴费成功模板未配置");
					}
					String tempId=msgTemplate.getTemplateId();
					JSONObject item=new JSONObject();
					item.put("openid",jwidModel.getOpenId());
					item.put("accCode",chargeFeeVo.getAccCode());
					item.put("url",jwidModel.getHdUrl());
					item.put("orderNo",rsObject.getString("paymentId"));
					item.put("jwidName",jwidModel.getName());
					item.put("money",chgPayments.getPayFee());
					msgPaySuccessTemplateSend(accessToken,tempId,item);
				}
				return result;
			}
		}
		return Result.error("预支付核销异常");
	}
	//手动核销
	@Override
	@Transactional
	public Result<?> queryOrderState(JwidModel jwidModel, ChgPayments chgPayments) {

			boolean prePayState=false;

			if(1 == chgPayments.getStatus() && oConvertUtils.isNotEmpty(chgPayments.getTransactionId())){
				//已支付成功- 回调已处理
				prePayState=true;
			}else{
				//查询预支付订单状态 payPreArr[1]
				try {
//					Result<?> preOrder = wxPayUtils.queryPreOrder(jwidModel, payPreArr[1]);
					/**
					 * 成功
					 * {"amount":{"currency":"CNY","payer_currency":"CNY","payer_total":1,"total":1},"appid":"wxbc93defb209eb818","attach":""
					 * ,"bank_type":"OTHERS","mchid":"1625344192","out_trade_no":"1531267686257803266","payer":{"openid":"ombUS6RxgmyyAi9aqdQsTeveWBeU"}
					 * ,"promotion_detail":[],"success_time":"2022-05-30T21:34:54+08:00","trade_state":"SUCCESS","trade_state_desc":"支付成功"
					 * ,"trade_type":"JSAPI","transaction_id":"4200001425202205302805017124"}
					 *
					 * 未成功
					 * {"amount":{"payer_currency":"CNY","total":34800},"appid":"wx50d1563f095ee8ba","mchid":"1367447802"
					 * ,"out_trade_no":"1538851496847728642","promotion_detail":[],"scene_info":{"device_id":""}
					 * ,"trade_state":"NOTPAY" * ,"trade_state_desc":"订单未支付"}
					 *
					 * */
					Result<?> preOrder = wxPayUtils.queryPreOrderNo(jwidModel, chgPayments.getId());
					if(preOrder.isSuccess()){
						JSONObject traObj=	JSONObject.parseObject(preOrder.getResult().toString());
						if(null !=traObj){
							if(oConvertUtils.isEmpty(traObj.getString("transaction_id"))){
								paymentsService.update(new LambdaUpdateWrapper<ChgPayments>()
										.set(ChgPayments::getDelFlag,1)//逻辑删除
										.set(ChgPayments::getRemark,traObj.getString("trade_state_desc"))
										.eq(ChgPayments::getId,chgPayments.getId()));
								return Result.error("该笔缴费订单："+traObj.getString("trade_state_desc"));
							}else {
								prePayState=true;
								chgPayments.setTransactionId(traObj.getString("transaction_id"));
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					return Result.error("预支付核销异常"+e.getMessage());
				}
			}

			if(prePayState){
				ArrayList arrearIds=null;

				if(1 == chgPayments.getStatus() && chgPayments.getSyncFlag() ==1) {
					return Result.error("已核销");
				}

				Result<?> result = chgFeesService.mpHeXiaoCharge(chgPayments);

				if(result.isSuccess()){
					//推送缴费成功通知
					JSONObject rsObject = (JSONObject) result.getResult();

					String accessToken = jwidModel.getAccessToken();
					JwMsgTemplateModel msgTemplate = sysBaseAPI.getMsgFeeBillTemplate(jwidModel.getId(), CommonSendStatus.MSG_PAY_SUCCESS_NOTICE);
					if(null == msgTemplate){
						return Result.error("缴费成功，缴费成功模板未配置");
					}
					String tempId=msgTemplate.getTemplateId();

					if(oConvertUtils.isNotEmpty( rsObject.getString("openId"))){
						JSONObject item=new JSONObject();
						item.put("openid",rsObject.getString("openId"));
						item.put("accCode",chgPayments.getAccCode());
						item.put("url",jwidModel.getHdUrl());
						item.put("orderNo",rsObject.getString("paymentId"));
						item.put("jwidName",jwidModel.getName());
						item.put("money",chgPayments.getPayFee());
						msgPaySuccessTemplateSend(accessToken,tempId,item);
					}
					result.setMessage("核销成功");
				}
				return result;
				//return chgFeesService.mpCharge(chargeFeeVo,chgPayments,arrearIds);
			}
		return Result.error("预支付核销异常");
	}

	//根据微信交易单号查询订单状态
	@Override
	public Result<?> queryWxtOrderState(JwidModel jwidModel, ChgPayments chgPayments) {

			//查询预支付订单状态 payPreArr[1]
			try {
//					Result<?> preOrder = wxPayUtils.queryPreOrder(jwidModel, payPreArr[1]);
				/**
				 * 成功
				 * {"amount":{"currency":"CNY","payer_currency":"CNY","payer_total":1,"total":1},"appid":"wxbc93defb209eb818","attach":""
				 * ,"bank_type":"OTHERS","mchid":"1625344192","out_trade_no":"1531267686257803266","payer":{"openid":"ombUS6RxgmyyAi9aqdQsTeveWBeU"}
				 * ,"promotion_detail":[],"success_time":"2022-05-30T21:34:54+08:00","trade_state":"SUCCESS","trade_state_desc":"支付成功"
				 * ,"trade_type":"JSAPI","transaction_id":"4200001425202205302805017124"}
				 *
				 * 未成功
				 * {"amount":{"payer_currency":"CNY","total":34800},"appid":"wx50d1563f095ee8ba","mchid":"1367447802"
				 * ,"out_trade_no":"1538851496847728642","promotion_detail":[],"scene_info":{"device_id":""}
				 * ,"trade_state":"NOTPAY" * ,"trade_state_desc":"订单未支付"}
				 *
				 * */
				Result<?> preOrder = wxPayUtils.queryWxtOrderNo(jwidModel, chgPayments.getTransactionId());
				if(preOrder.isSuccess()){
					JSONObject traObj=	JSONObject.parseObject(preOrder.getResult().toString());
					return Result.OK(traObj);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Result.error("查询异常"+e.getMessage());
			}

		return Result.error("查询异常");
	}

	public Result<?>  QueryOrder(JwidModel jwidModel,String prepayId) throws Exception {

		return	wxPayUtils.queryPreOrder(jwidModel,prepayId);
	}


	public Result<?> createMpOrderPage(JwidModel jwidModel, JSONObject orderObj) throws UnsupportedEncodingException {

		JSONObject jsonObject = wxPayUtils.buildWxJsApiPayJson(
				jwidModel.getWeixinAppid()
				,jwidModel.getWeixinMchid()
				,"截止"+ DateUtils.getDate("yyyyMM")+"水费"
				,orderObj.getString("paymentId")
				,orderObj.getString("notifyUrl")
				,orderObj.getString("amount"),
				orderObj.getString("openId"));

		JSONObject attachObj = new JSONObject();
		attachObj.put("tenantId",jwidModel.getTenantId());
		attachObj.put("jwid",jwidModel.getJwid());

		jsonObject.put("attach",attachObj.toString());//附加数据


		WeChatPayModel payModel = new WeChatPayModel();
		payModel.setAccessToken(jwidModel.getAccessToken());
		payModel.setJwid(jwidModel.getJwid());
		payModel.setToken(jwidModel.getToken());
		payModel.setWeixinAppid(jwidModel.getWeixinAppid());
		payModel.setWeixinMchid(jwidModel.getWeixinMchid());
		payModel.setWeixinMchkey(jwidModel.getWeixinMchkey());
		payModel.setMchSerialNo(jwidModel.getMchSerialNo());
		//payModel.setWeixinAppsecret(jwidModel.getWeixinAppsecret());
		payModel.setMchPrivateKeyStr(jwidModel.getMchkeyPath());
		payModel.setTenantId(jwidModel.getTenantId());

		JSONObject mpResObj = wxPayUtils.doPostWexinV3(payModel
				, "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"
				, jsonObject.toJSONString());
		//System.out.println(mpResObj.toJSONString());
		if(mpResObj.containsKey("errcode") && !"0".equals(mpResObj.getString("errcode"))){
			return Result.error(mpResObj.getString("errmsg"));
		}

		return Result.OK(mpResObj);
	}

	/**
	 * 验证签名
	 *
	 * @param serialNo  微信平台-证书序列号
	 * @param signStr   自己组装的签名串
	 * @param signature 微信返回的签名
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private boolean verifiedSign(JwidModel jwidModel,String serialNo, String signStr, String signature) throws Exception {
		return wxPayUtils.verifySigna(jwidModel,serialNo, signStr, signature);
	}

	/**缴费成功通知 MSG_PAY_SUCCESS_NOTICE
	 {{first.DATA}}
	 收费单位：{{keyword1.DATA}}
	 缴费账号：{{keyword2.DATA}}
	 交易时间：{{keyword3.DATA}}
	 缴费金额：{{keyword4.DATA}}
	 {{remark.DATA}}

	 你的订单已缴费成功。
	 收费单位：深圳供电局（关内区）
	 缴费账号：111111
	 交易时间：2013-12-10 10:17:57
	 缴费金额：100.
	 00元您可以到缴费记录查看更多信息

	 * **/
	public void msgPaySuccessTemplateSend(String accessToken,String temId, JSONObject item){

		JSONObject noteItem=new JSONObject();

		noteItem.put("openid",item.getString("openid"));
		noteItem.put("accCode",item.getString("accCode"));
		noteItem.put("url",item.getString("url"));

		noteItem.put("first","恭喜您水费缴费成功，本次缴费订单号:"+item.getString("orderNo"));
		noteItem.put("keynote1",item.getString("jwidName"));
		noteItem.put("keynote2",item.getString("accCode"));
		noteItem.put("keynote3",DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));

		//缴费金额
		noteItem.put("keynote4",item.getBigDecimal("money").setScale(2, BigDecimal.ROUND_HALF_UP)+"元");
		noteItem.put("remark","您可以到缴费记录查看更多信息");

		JSONObject jsonObject = sysBaseAPI.msgSend(accessToken, temId, noteItem);
		log.debug(new Date()+"-msgSend发送微信消息结果："+jsonObject.toJSONString());
	}
}
